/**
 * 定时计时器
 **/
public class ExecutionTimer {
    // 上一次记录时间
    private long lastRecordedTime = 0L;
    // ANSI转义序列开始（红色）
    private static final String ANSI_RED = "\u001B[31m";
    // ANSI转义序列结束（重置颜色）
    private static final String ANSI_RESET = "\u001B[0m";

    /* 开始或重置计时器 */
    public void start() {
        lastRecordedTime = System.nanoTime();
    }

    /* 计算上一次调用的时间 */
    public void logTime(String... identifier) {
        long currentTime = System.nanoTime();
        long duration = (currentTime - lastRecordedTime) / 1_000_000;
        String formattedTime = formatDuration(duration);
        if (identifier.length > 0) {
            System.out.println(ANSI_RED + "[" + identifier[0] + "]-运行时间:" + formattedTime + ANSI_RESET);
        } else {
            System.out.println(ANSI_RED + "运行时间：" + formattedTime + ANSI_RESET);
        }
        lastRecordedTime = currentTime;
    }

    /* 格式化时间 */
    private String formatDuration(long durationMillis) {
        long minutes = durationMillis / 60000;
        long seconds = (durationMillis % 60000) / 1000;
        long millis = durationMillis % 1000;
        return String.format("%d分钟%d秒%d毫秒", minutes, seconds, millis);
    }

}